package org.fight.landowner.common.serialize;

import com.alibaba.fastjson.JSON;
import org.fight.landowner.common.util.ByteUtil;
import org.fight.landowner.common.util.ClazzUtil;

import java.nio.charset.StandardCharsets;

/**
 * @Author wangxuehao02
 * @Date 2024/2/8 4:18 PM
 * @Description
 **/
public class BytesJSONSerializer implements BytesSerializer {
    @Override
    public byte[] serialize(Object data) {
        if (data == null) {
            return ByteUtil.EMPTY_BYTE_ARRAY;
        }

        if (ClazzUtil.isBaseType(data.getClass()) || data.getClass() == String.class) {
            return data.toString().getBytes(StandardCharsets.UTF_8);
        }

        return JSON.toJSONString(data).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public <T> T deSerialize(byte[] data, Class<T> clazz) {
        if (String.class == clazz) {
            return (T) new String(data, StandardCharsets.UTF_8);
        }

        return JSON.parseObject(data, clazz);
    }

}
